<template>
  <div>
    <button @mousedown="recStart" ref="btnRef">开始录制</button>
    <div
      style="
        height: 100px;
        width: 300px;
        border: 1px solid #ccc;
        box-sizing: border-box;
        display: inline-block;
        vertical-align: bottom;
      "
      class="ctrlProcessWave"
    ></div>

    <div class="mainBox">
      <audio ref="LogAudioPlayer" style="width: 100%"></audio>
      <div class="mainLog">
        <div v-for="obj in logs" :key="obj.idx">
          <div
            :style="{
              color:
                obj.color == 1 ? 'red' : obj.color == 2 ? 'green' : obj.color,
            }"
          >
            <!-- <template v-once> 在v-for里存在的bug，参考：https://v2ex.com/t/625317 -->
            <span v-once>[{{ getTime() }}]</span><span v-html="obj.msg" />

            <template v-if="obj.res">
              {{ intp(obj.res.rec.set.bitRate, 3) }}kbps
              {{ intp(obj.res.rec.set.sampleRate, 5) }}hz 编码{{
                intp(obj.res.blob.size, 6)
              }}b [{{ obj.res.rec.set.type }}]{{ intp(obj.res.duration, 6) }}ms

              <button @click="recdown(obj.idx)">下载</button>
              <button @click="recplay(obj.idx)">播放</button>

              <span v-html="obj.playMsg"></span>
              <span v-if="obj.down">
                <span style="color: red">{{ obj.down }}</span>

                没弹下载？试一下链接或复制文本<button
                  @click="recdown64(obj.idx)"
                >
                  生成Base64文本
                </button>

                <textarea
                  v-if="obj.down64Val"
                  v-model="obj.down64Val"
                ></textarea>
              </span>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/********加载RecordApp需要用到的支持文件*********/
//必须引入的app核心文件，换成require也是一样的。注意：app.js会自动往window下挂载名称为RecordApp对象，全局可调用window.RecordApp，也许可自行调整相关源码清除全局污染
import RecordApp from "recorder-core/src/app-support/app";
//可选开启Native支持，需要引入此文件
import "recorder-core/src/app-support/app-native-support";
//可选开启IOS上微信录音支持，需要引入此文件
import "recorder-core/src/app-support/app-ios-weixin-support";

/*********加载Recorder需要的文件***********/
//必须引入的核心，所有需要的文件都应当引入，引入后会检测到组件已自动加载
//不引入也可以，app.js会去用script动态加载，应确保app.js内BaseFolder目录的正确性(参阅RecordAppBaseFolder)，否则会导致404 js加载失败
import Recorder from "recorder-core";

//【要打包到一个js就解开注释】本demo是通过script动态引入这些引擎js文件
//需要使用到的音频格式编码引擎的js文件统统加载进来，这些引擎文件会比较大
//【解开】import 'recorder-core/src/engine/mp3'
//【解开】import 'recorder-core/src/engine/mp3-engine'
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
import "recorder-core/src/engine/wav";
// import "recorder-core/src/engine/wav-engine";
//由于大部分情况下ios-weixin的支持需要用到amr解码器，应当把amr引擎也加载进来，这些引擎文件会比较大
//【解开】import 'recorder-core/src/engine/beta-amr'
//【解开】import 'recorder-core/src/engine/beta-amr-engine'
//【解开】import 'recorder-core/src/engine/wav' //amr依赖了wav引擎

//可选的扩展支持项
import "recorder-core/src/extensions/waveview";
import axios from "axios";
export default {
  data() {
    return {
      App: RecordApp,
      Rec: Recorder,

      type: "wav",
      bitRate: 16,
      sampleRate: 16000,

      rec: false,
      duration: 0,
      powerLevel: 0,

      recOpenDialogShow: 0,
      logs: [],
    };
  },
  mounted() {
    this.recReq();
    let btnRef = this.$refs.btnRef;
    console.log(btnRef);
    btnRef.addEventListener("mouseup", () => {
      this.recStop();
    });
  },
  methods: {
    // 请求权限
    recReq() {
      this.rec = false;
      //   this.dialogInt = setTimeout(function () {
      //定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
      // this.showDialog();
      //   }, 8000);
      RecordApp.RequestPermission(
        () => {
          this.rec = true;
          //   this.dialogCancel();

          this.reclog("已打开录音，可以点击录制开始录音了", 2);
        },
        function (err, isUserNotAllow) {
          //   this.dialogCancel();
          this.reclog(
            (isUserNotAllow ? "UserNotAllow，" : "") + "打开录音失败：" + err,
            1
          );
        }
      );
      this.waitDialogClickFn = function () {
        // this.dialogCancel();
        this.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗", 1);
      };
    },
    // 开始录制
    recStart: function () {
      var This = this;
      if (!This.rec || !RecordApp.Current) {
        console.log(This.rec, RecordApp.Current);
        This.reclog("未请求权限", 1);
        return;
      }

      if (RecordApp.Current == RecordApp.Platforms.Weixin) {
        This.reclog("正在使用微信JsSDK，录音过程中不会有任何回调，不要惊慌");
      } else if (RecordApp.Current == RecordApp.Platforms.Native) {
        This.reclog("正在使用Native录音，底层由App原生层提供支持");
      } else {
        This.reclog("正在使用H5录音，底层由Recorder直接提供支持");
      }

      var set = {
        type: This.type,
        bitRate: This.bitRate,
        sampleRate: This.sampleRate,
        onProcess: function (buffers, powerLevel, duration, sampleRate) {
          This.duration = duration;
          This.powerLevel = powerLevel;

          This.wave.input(buffers[buffers.length - 1], powerLevel, sampleRate);
        },
      };

      RecordApp.Start(
        set,
        function () {
          This.reclog(
            RecordApp.Current.Key +
              "录制中:" +
              set.type +
              " " +
              set.bitRate +
              "kbps",
            2
          );

          //此处创建这些音频可视化图形绘制浏览器支持妥妥的
          This.wave = Recorder.WaveView({ elem: ".ctrlProcessWave" });
        },
        function (err) {
          This.reclog(RecordApp.Current.Key + "开始录音失败：" + err, 1);
        }
      );
    },
    // 停止录制
    recStop: function () {
      var This = this;
      var rec = This.rec;
      This.rec = false;

      if (!rec || !RecordApp.Current) {
        This.reclog("未请求权限", 1);
        return;
      }

      RecordApp.Stop(
        function (blob, duration) {
          This.reclog("已录制:", "", {
            blob: blob,
            duration: duration,
            rec: RecordApp.GetStopUsedRec(),
          });
          This.downLoad(blob);
          This.uoLoad(blob);
          This.recReq();
        },
        function (msg) {
          This.reclog("录音失败：" + msg, 1);
        }
      );
    },
    // 下载
    downLoad(blob) {
      console.log("调用了下载方法");
      let aLink = document.createElement("a");
      aLink.href = URL.createObjectURL(blob);
      aLink.setAttribute("download", "qwe.wav"); // 设置下载文件名称
      document.body.appendChild(aLink);
      aLink.click();
      URL.revokeObjectURL(aLink.href); //释放url
      document.body.appendChild(aLink);
    },
    // 上传
    uoLoad(blob) {
      let file = new window.File([blob], "123.wav", {
        type: "audio/wav",
        lastModified: Date.now(),
      });
      console.log(file);
      let paramsData = new FormData();
      paramsData.append(`file`, file);
      console.log(axios);
      axios({
        url: "http://192.168.2.21:8084/zhijian/zhijianlink/getBlobToWav",
        method: "POST",
        data: paramsData,
        headers: { "Content-Type": "multipart/form-data" },
      }).then(({ res }) => {
        console.log("res", res);
      });
    },
    // 打印
    reclog(str, color, res) {
      console.log(str);
      this.$message("str");
    },
  },
};
</script>

<style>
</style>